package com.cobla.struct.matrix.ten;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 十字链表<br/>
 * 头节点
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CrossList {
    // 指向同一行下一个有值的指针
    // 指向同一列下一个有值的指针
    private OlNode[] rHead, cHead;
    // 矩阵 行数 列数 非零节点个数
    int  row, col, total;


    /**
     * 给定 矩阵{@param A}, 返回其非零元素的十字链表
     * @param A
     * @return
     */
    public static CrossList createCrossListFromMatrix(float[][] A){
        CrossList cl = new CrossList(new OlNode[A.length], new OlNode[A[0].length], A.length, A[0].length, 0);

        for (int i = 0; i < cl.getRHead().length; i++) {
            cl.getRHead()[i] = new OlNode(-1, -1, null, null, 0);
        }
        for (int i = 0; i < cl.getCHead().length; i++) {
            cl.getCHead()[i] = new OlNode(-1, -1, null, null, 0);
        }

        for (int i = A.length - 1; i >= 0; i--) {
            for (int j = A[0].length - 1; j >= 0; j--) {
                // 插入
                if (A[i][j] != 0) {
                    OlNode right = cl.getRHead()[i].getRight();
                    OlNode down = cl.getCHead()[j].getDown();
                    OlNode node = new OlNode(i, j, right, down, A[i][j]);
                    cl.getCHead()[j].setDown(node);
                    cl.getRHead()[i].setRight(node);
                    cl.setTotal(cl.getTotal()+1);
                }
            }
        }
        return cl;
    }
}
